﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using System.Diagnostics;
using Compiled_Tests.Utils;
using LEET.CommonInterfaces.Automation;
using LEET.LEETCommon;

namespace Compiled_Tests.AutomationAbstractions
{
    public class ObservableWidget : AEWrapper, IObservableWidget
    {
        public ObservableWidget(AutomationElement ae) : base (ae)
        {
        }

        public bool ProccessHasExited
        {
            get
            {
                try{
                    return Process.GetProcessById(ProcessID).HasExited;
                } catch {
                    return true;
                }
            }
        }

        
        /// <summary>
        /// Returns the path from the root AutomationElement to the given AutomationElement as a string.
        /// </summary>
        /// <param name="current">The AutomationElement to </param>
        /// <param name="element"></param>
        public virtual IUIPath GetUIAHierarchy(IObservableWidget rootAE)
        {
            IUIPath path;
            try
            {

                if (this.Equals(rootAE) || Parent == null)
                {
                    path = new UIPath();
                }
                else
                {
                    path = (Parent as ObservableWidget).GetUIAHierarchy(rootAE);
                    path.Add(FindValidIdentifier());
                }
                return path;
            }
            catch (ElementNotAvailableException)
            {
                return new UIPath();
            }
        }

        protected PathElement FindValidIdentifier()
        {
            return new PathElement(ID, Utilities.Escape(Name), Class);
        }


        public virtual string Value
        {
            get { 
                Object obj;
                ValuePattern pattern;
                TryGetCurrentPattern(ValuePattern.Pattern, out obj);
                if (obj != null)
                {
                    pattern = (ValuePattern)obj;
                    return pattern.Current.Value;
                }
                else
                {
                    return "";
                }
            }
        }


        public virtual bool HasPattern(AutomationPattern pattern)
        {
            object obj;
            TryGetCurrentPattern(pattern, out obj);
            return obj != null;
        }


        public virtual bool IsReadOnly
        {
            get 
            {
                return !IsEnabled;
            }
        }

        protected override AEWrapper Wrap(AutomationElement element)
        {
            return new ObservableWidget(element);
        }

    }
}
